package com.atguigu.test01;


import java.util.concurrent.locks.ReentrantLock;

class took{
    private int cooks=30;

    public int getCooks() {
        return cooks;
    }

    ReentrantLock lock = new ReentrantLock();
    public void save() throws InterruptedException {
        lock.lock();
        if (cooks<=0){
            System.out.println("已售完");
            System.out.println("--------------------------------------------");
            lock.unlock();
            return;
        }
        Thread.sleep(200);
        System.out.println(Thread.currentThread().getName()+" 售票前"+cooks+"张");
        cooks--;
        System.out.println(Thread.currentThread().getName()+" 售票后"+cooks+"张");
        System.out.println("--------------------------------------------");
        lock.unlock();
    }
}


public class test01 {

    public static void main(String[] args) {
        took took = new took();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                try {
                    took.save();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                if (took.getCooks()<=0){
                    break;
                }

            }
        },"t1").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                try {
                    took.save();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (took.getCooks()<=0){
                    break;
                }
            }
        },"t2").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                try {
                    took.save();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (took.getCooks()<=0){
                    break;
                }
            }
        },"t3").start();
    }

}
